<template>
  <div class="flex h-full">
    <a-card
      v-if="showType === '1'"
      class="pt-2 mr-2 min-w-fit h-full"
      size="small"
      :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }"
    >
      <SearchComb v-model:value="searchCombData" class="w-56" placeholder="姓名/助记码/卡号/手机号/身份证号" @search="getList()" />
      <BaseList :data-source="listDataSource" :loading="loading" class="flex-1 overflow-auto">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="patientId === item.jzbh ? 'active' : ''" @click="onSelectPatient(item)">
            <div class="flex justify-between">
              <div class="flex items-center w-24" :title="item.brName">
                <div class="text-base font-bold text-primary truncate mr-2">{{ item.brName }}</div>
                <a-button v-if="item.czfz === '初诊'" type="primary" shape="circle" size="small">初</a-button>
                <a-button v-if="item.czfz === '复诊'" type="primary" shape="circle" size="small" class="bg-orange-400">复</a-button>
              </div>
              <div class="text-primary">未发药</div>
            </div>
            <div class="flex justify-between pt-2">
              <div class="text-right text-grey">{{ item.sfsj }}</div>
              <div class="w-20 text-grey text-right">{{ item.rysx || '-' }}</div>
            </div>
          </div>
        </template>
      </BaseList>
      <a-form>
        <SelectDrugRoom
          v-model:value="drugStoreId"
          :params="{ isProducer: '1' }"
          select-first
          placeholder="选择药房"
          class="w-full mb-2"
          @select="onSelectDrugRoom"
        />
        <a-form-item class="w-full" label="">
          <a-select v-model:value="reviewer" :options="pharmacistSelectData" placeholder="选择审核人" />
        </a-form-item>
      </a-form>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <ReadCard v-if="showType === '3'" business-type="门诊发药" :call-back-data="readCallData" @read="onReadCard" @tab-change="onReset" />

      <SearchContainer v-if="showType !== '1'" search-text="刷新" @search="getTableData" @reset="onReset">
        <div class="flex justify-between">
          <a-form ref="formRef" class="form-style-flex w-full" :model="searchData" :label-col="{ style: { width: '80px' } }">
            <a-form-item label="" name="brName" class="w-80">
              <SelectTable
                v-model:value="searchData.brName"
                :search-params="{ stdate: searchData['dateRange']?.[0], eddate: searchData['dateRange']?.[1], lb: 0, drugStoreId }"
                type="已收费患者列表"
                :disabled="!drugStoreId"
                placeholder="姓名/助记码/卡号/手机号/身份证号/票据号"
                @select="onSelectPatient"
              />
            </a-form-item>
            <a-form-item label="收费日期" name="dateRange">
              <a-range-picker v-model:value="searchData['dateRange']" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :allow-clear="false" />
            </a-form-item>
            <div class="flex flex-1 justify-end">
              <SelectDrugRoom
                v-model:value="drugStoreId"
                placeholder="选择药房"
                select-first
                :params="{ isProducer: '1' }"
                class="w-64 mb-2 mr-4"
                @select="onSelectDrugRoom"
              />
              <a-form-item class="w-64" label="审核人">
                <a-select v-model:value="reviewer" :options="pharmacistSelectData" placeholder="请选择" />
              </a-form-item>
            </div>
          </a-form>
        </div>
      </SearchContainer>
      <PatientInfoHeader :patient-info="patientInfo" :show-insurance="!isArmy">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-2" label="卡号" :width="160" :value="patientInfo?.brId" />
            <LabelValue class="ml-2" label="病案号" :value="patientInfo[isBGMSG ? 'brBlkh' : 'oprSn']" :width="160" />
            <LabelValue class="ml-2" label="科室" :width="140" :value="patientInfo?.ksmc" />
            <LabelValue class="ml-2" label="类别" :width="140" :value="patientInfo?.ghlb" />
            <!-- <LabelValue class="ml-2" label="过敏史" :width="280" :tooltip="true" :value="patientInfo?.brGms" /> -->
            <AllergyHistory class="ml-4" :width="280" :value="patientInfo.brGms" :patient-info="patientInfo" @success="(e) => (patientInfo.brGms = e)" />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-2" label="门诊号" :width="160" :value="patientInfo?.jzbh" />
            <LabelValue class="ml-2" label="病历号" :value="patientInfo[isBGMSG ? 'oprSn' : 'brBlkh']" :width="160" />
            <LabelValue class="ml-2" label="医生" :width="140" :value="patientInfo?.empName" />
            <LabelValue class="ml-2" label="时间" :width="140" :value="patientInfo?.sfsj" />
            <LabelValue class="ml-2" label="初步诊断" :width="320" :value="patientInfo?.zdmc" />
          </div>
        </div>
      </PatientInfoHeader>
      <a-card class="mt-2 w-full flex-1">
        <a-tabs v-model:active-key="medicineType" destroy-inactive-tab-pane @change="onTabChange">
          <template #rightExtra>
            <div class="flex">
              <div v-if="showType === '3'" class="w-96 flex items-center justify-end mr-2 truncate">
                <div :title="drugInfo.mc" class="font-semibold">{{ drugInfo.mc }}</div>
                <div v-if="drugInfo.gg" :title="drugInfo.gg" class="text-gray-400 ml-2 text-xs">{{ drugInfo.gg }}</div>
                <div v-if="drugInfo.cj" :title="drugInfo.cj" class="text-gray-400 ml-2 text-xs w-20 truncate">{{ drugInfo.cj }}</div>
              </div>
              <a-form v-if="medicineType === '西药/中成药'" class="flex" :disabled="tableData.length === 0">
                <a-input
                  v-if="showType === '3'"
                  ref="scInputRef"
                  v-model:value="scInput"
                  placeholder="请扫追溯码"
                  maxlength="20"
                  class="mr-4"
                  @keydown.enter="onCodeEnter"
                />
                <a-button type="primary" @click="onDispensing"> 批量发药 </a-button>
              </a-form>
              <a-form v-else class="flex" :disabled="!patientId">
                <a-button type="primary"> 发药 </a-button>
              </a-form>
            </div>
          </template>
          <a-tab-pane key="西药/中成药">
            <template #tab>
              <a-badge :count="prescriptionCount.cfsl || 0" :offset="[10, -2]"> 西药/中成药 </a-badge>
            </template>
            <a-card class="mt-2 w-full flex-col flex-1 overflow-auto overflow-x-hidden" style="height: calc(100vh - 370px)">
              <a-spin :spinning="tableLoading" class="w-full pt-40">
                <template v-if="tableData.length">
                  <template v-for="(tableItem, tableIndex) in tableData" :key="tableItem.tableKey">
                    <BaseTable
                      bordered
                      column-code="00001027"
                      :pagination="false"
                      row-key="id"
                      :expanded-row-keys="tableItem.expandedRowKeys"
                      :exclude-columns="showType !== '3' ? ['zsm'] : []"
                      :row-selection="{
                        checkStrictly: false,
                        selectedRowKeys: tableItem.selectedRowKeys,
                        onChange: (val) => onSelectChange(val, tableItem)
                      }"
                      :data-source="tableItem.dataSource"
                    >
                      <template #title>
                        <div class="flex justify-between items-center">
                          <div class="flex">
                            <div class="font-bold mr-2">处方{{ tableIndex + 1 }}:{{ tableItem.cfbh }}</div>
                            <div class="ml-4">{{ tableItem.dataSource[0].drugStoreName }}</div>
                            <a-tag v-if="patientInfo.brAge?.replace('岁', '') < 15" color="green" class="ml-4">儿童处方</a-tag>
                            <a-tag v-else color="blue" class="ml-4"> 普通处方</a-tag>
                          </div>
                          <a-space>
                            <a-button type="primary" ghost @click="onPrintLabel(tableItem)"> 打印标签 </a-button>
                            <a-button type="primary" ghost @click="onClickPrint(tableItem)"> 打印处方单 </a-button>
                          </a-space>
                        </div>
                      </template>
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'link'">
                          <div class="table-link"></div>
                        </template>
                        <template v-if="column.dataIndex === 'sfxm'">
                          <MedicineInfo :value="{ mc: record.sfxm?.mc, gg: record.sfxm?.gg, cj: record.sfxm?.cj, skinTestFlag: record.sfxm?.skinTestFlag }" />
                        </template>
                        <template v-if="column.dataIndex === 'yf'">
                          {{ record.yf?.fyff }}
                        </template>
                        <template v-if="column.dataIndex === 'dj'">
                          {{ record.sfxm?.dj }}
                        </template>
                        <!-- 追溯码 -->
                        <template v-if="column.dataIndex === 'zsm'">
                          <span :class="record.isScAll ? '' : 'text-red-500'"> {{ record.scList?.length || 0 }}/{{ record.sl }} </span>
                          <a-radio
                            v-if="!isCheckTcCode"
                            :checked="selectRadio.sfxmbh === record.sfxmbh && selectRadio.cfbh === tableItem.cfbh"
                            class="ml-2"
                            @click="onChangeRadio({ ...record, cfbh: tableItem.cfbh })"
                          />
                        </template>
                        <template v-if="column.dataIndex === 'pl'">
                          {{ record.pl?.pl }}
                        </template>
                        <template v-if="column.dataIndex === 'zxdwsl'"> {{ record.jlsl }} {{ record.sfxm.jldw }} </template>
                        <template v-if="column.dataIndex === 'cfts'"> {{ record.cfts }}天 </template>
                        <template v-if="column.dataIndex === 'sl'"> {{ record.sl }}{{ record.sfxm.dw }} </template>
                      </template>
                    </BaseTable>
                  </template>
                </template>
                <a-empty v-else description="请选择患者" class="mt-10" />
              </a-spin>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="中草药">
            <template #tab>
              <a-badge :count="prescriptionCount.zycfsl || 0" :offset="[10, -2]"> 中草药 </a-badge>
            </template>
            <TabTCM v-if="patientId" ref="tabTCMRef" :jzbh="patientId" disabled />
            <a-empty v-else class="mt-[60px]" description="请选择患者" />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
    <SelectRegisterModal v-model:open="openSelectModal" :resource-data="allRegisterData" @ok="onSelectRegister" />
  </div>
</template>

<script setup>
import { ref, onMounted, toRaw } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import SearchComb from '@/components/SearchComb'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
// import { formatDate } from '@/utils/format'
import BaseList from '@/components/BaseList'
import { getSystemConfig } from '@/utils/systemConfig'
import cofirmModal from '@/utils/confirm.js'
import useUserStore from '@/store/user'

import TabTCM from '@/views/out-doctor/workstation/TabTCM/index.vue'
import SelectRegisterModal from './components/SelectRegisterModal'

const { empId } = useUserStore()
const showType = getSystemConfig('OUTDISPENSING_STYLE') || '1' //门诊发药界面样式
const isPrint = getSystemConfig('PRESCRIPTION_FORM_PRINT_MODE') //处方单打印模式
const isAutomatic = getSystemConfig('DISPENSING_AUTO_PRINT_LABEL') === '1' //0:不启用1:启用标签
const isPrescription = getSystemConfig('OUTP_DISPENSING_AUTO_PRINT_PRESCRIPTION') === '1' //0:不启用1:启用处方单
const tabTCMRef = ref(null)

const medicineType = ref('西药/中成药')
const listDataSource = ref([])
const prescriptionCount = ref({})
const formRef = ref(null)
const searchCombData = ref({})
const pharmacistSelectData = ref([])
const reviewer = ref(undefined) //审核人
const drugStoreId = ref(undefined) //发药药房
const searchData = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const patientId = ref('') //就诊编号
const patientInfo = ref({})
const loading = ref(false)
const isArmy = ref(false)
const drugInfo = ref({})
const selectRadio = ref({})
const openSelectModal = ref(false)
const allRegisterData = ref([])
const tabActiveKey = ref('自费')
const readCallData = ref({})
//获取患者信息
// const patientInfo = usePatient(patientId, '门诊')

const getTableData = () => {
  patientId.value && getData()
}

//获取门诊患者信息
const getOutpatientInfo = async () => {
  const { data, code } = await post('/outp/mzys/getOutpRecordInfo', { mzjlbh: patientId.value })
  if (code === 0) {
    patientInfo.value = data
    searchData.value.brName = data.brName
  }
}

// const onChangeInfo = () => {
//   if (showType === '1') {
//     getList(formState.value)
//   } else {
//     // getOutpatientInfo()
//     onReset()
//   }
// }

//获取西药/中成药
const {
  loading: tableLoading,
  tableData,
  getData
} = useTable({
  url: '/outp/mzys/getPatientPrescriptionInfoList',
  pagination: false,
  immediate: false,
  formatParams: () => {
    return {
      jzbh: patientId.value,
      zxzt: 0,
      jfzt: '1',
      drugStoreId: drugStoreId.value
    }
  },
  formatResult: (results) => {
    return results.map((item) => {
      return {
        cfbh: item.cfbh,
        selectedRowKeys: getIds(item.children),
        expandedRowKeys: item.children.map((item) => item.id) || [],
        dataSource: item.children.map((child) => ({
          ...child,
          key: child.id,
          children: child.children.map((c) => ({ ...c, isChild: true, cfbh: item.cfbh, fkey: child.id, key: c.id }))
        }))
      }
    })
  }
})
//获取所有数据的id，包括父级和子级
const getIds = (data) => {
  const ids = []
  data.forEach((item) => {
    ids.push(item.id)
    if (item.children.length > 0) {
      item.children.forEach((child) => {
        ids.push(child.id)
      })
    }
  })
  return ids
}
const onSelectChange = (keys, table) => {
  table.selectedRowKeys = keys
}
const getSelectedIds = () => {
  const tableDataCopy = toRaw(tableData.value)
  const selectObj = {
    jzbh: '',
    fyshr: '',
    yzList: []
  }
  if (medicineType.value === '西药/中成药') {
    if (tableDataCopy.map((item) => item.selectedRowKeys).flat().length === 0) {
      message.error('请选择发药项目')
      return
    }
    if (!reviewer.value) {
      message.error('请选择审核人')
      return
    }
    selectObj.jzbh = patientInfo.value.jzbh
    selectObj.fyshr = reviewer.value
    const yzObj = {
      cfbh: '',
      drugStoreId: '',
      idList: []
    }
    const scList = []
    tableDataCopy.forEach((item) => {
      if (item.selectedRowKeys.length > 0) {
        yzObj.cfbh = item.cfbh
        yzObj.isScAll = item.isScAll
        yzObj.drugStoreId = item.dataSource[0].drugStoreId
        yzObj.idList = item.selectedRowKeys
        selectObj.yzList.push(JSON.parse(JSON.stringify(yzObj)))
        item.dataSource.forEach((child) => {
          if (child.scList?.length) {
            scList.push({ mzyzbID: child.id, drugName: child.mc, sl: child.sl, isScAll: child.isScAll, tcCodeList: child.scList })
          }
        })
      }
      yzObj.cfbh = ''
      yzObj.drugStoreId = ''
      yzObj.idList = []
    })
    selectObj.tcList = scList
  } else if (medicineType.value === '中草药') {
    if (tabTCMRef.value.checkboxValue.length === 0) {
      message.error('请选择发药项目')
      return
    }
    if (!reviewer.value) {
      message.error('请选择审核人')
      return
    }
    selectObj.jzbh = patientInfo.value.jzbh
    selectObj.fyshr = reviewer.value
    const selectList = []
    tabTCMRef.value.orderDataSource.forEach((item) => {
      if (tabTCMRef.value.checkboxValue.includes(item.cfbh)) {
        selectList.push(item)
      }
    })
    const yzObj = {
      cfbh: '',
      drugStoreId: '',
      idList: []
    }
    selectList.forEach((item) => {
      yzObj.cfbh = item.cfbh
      yzObj.drugStoreId = item.drugStoreId
      yzObj.idList = item.children.map((item) => item.yzid).flat()
      selectObj.yzList.push(JSON.parse(JSON.stringify(yzObj)))
      yzObj.cfbh = ''
      yzObj.drugStoreId = ''
      yzObj.idList = []
    })
  }
  return selectObj
  // return selectedIds
}
//获取审核人下拉（类别为药剂师）
const getSelectPharmacist = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    emplbid: '5',
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999,
    notEmpIdList: [empId] // 当前登录但id
  })
  if (code !== 0) return
  pharmacistSelectData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
  const reviewerValue = JSON.parse(window.localStorage.getItem('dispensingReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    //保存24小时
    if (dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') >= 0 && dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') < 24) {
      reviewer.value = reviewerValue.value
    }
  }
}
const onSelectDrugRoom = (val) => {
  drugStoreId.value = val.id
  window.localStorage.setItem(
    'dispensingDrugStoreId',
    JSON.stringify({
      value: drugStoreId.value
    })
  )
  onReset()
  showType === '1' && getList()
}
const setLocalStorageEvent = () => {
  window.localStorage.setItem(
    'dispensingReviewer',
    JSON.stringify({
      time: dayjs().format(),
      value: reviewer.value
    })
  )
}
//发药
const onDispensing = async () => {
  if (!reviewer.value) return message.error('请选择审核人')
  // 标签自动打印
  if (isAutomatic) {
    tableData.value.forEach(async (i) => {
      await onPrintLabel(i)
    })
  }
  // 处方单自动打印
  if (isPrescription) {
    tableData.value.forEach(async (i) => {
      await onClickPrint(i)
    })
  }
  const params = getSelectedIds()
  if (params.tcList?.length && params.tcList.find((item) => !item.isScAll)) {
    const isConfirm = await cofirmModal({ title: '提示', content: '药品追溯码未扫描完整，是否继续发药？' })
    if (!isConfirm) return
  }
  const reviewerValue = JSON.parse(window.localStorage.getItem('dispensingReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    if (reviewerValue.value !== reviewer.value) {
      setLocalStorageEvent()
    }
  } else {
    setLocalStorageEvent()
  }
  if (!params || params.length === 0) return
  // return
  const res = await post('/outp/mzyf/doDistributeDrugNew', params)
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success('发药成功')
  medicineType.value === '西药/中成药' ? getTableData() : tabTCMRef.value.getData()
  showType === '1' && getList()
  showType === '2' && getPrescriptionCount()
  onReset()
}
//左侧数据
const getList = async (params = {}) => {
  const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingDrugStoreId'))
  if (drugStoreIdValue && drugStoreIdValue.value) {
    drugStoreId.value = drugStoreIdValue.value
  }
  if (!drugStoreId.value) return
  loading.value = true
  // /outp/mzyf/getExecuteClinicalOrderInfoList
  const { data = [] } = await post('/outp/mzyf/getOutpRecordListByClinicalOrderMZYF', {
    pyjm: searchCombData.value.searchKey,
    eddate: searchCombData.value.endDate,
    stdate: searchCombData.value.startDate,
    drugStoreId: drugStoreId.value,
    xmlbs: [2, 4, 5],
    lb: 0,
    ...params
  })
  loading.value = false
  listDataSource.value = data
  if (data.length > 0) {
    if (data.length > 1 && tabActiveKey.value !== '自费') {
      allRegisterData.value = data
      openSelectModal.value = true
    } else {
      onSelectRegister(data[0])
    }
  } else {
    params.brId && message.error('没有数据')
    patientId.value = ''
    tableData.value = []
    prescriptionCount.value = {}
  }
}
const onSelectRegister = (select) => {
  patientId.value = select.jzbh
  readCallData.value.medTypeName = select?.medTypeName
  readCallData.value.insutypeName = select?.insutypeName
  onSelectPatient(select)
}
const onTabChange = (key) => {
  key === '西药/中成药' && getTableData()
}
const onSelectPatient = (row) => {
  patientId.value = row.jzbh
  searchData.value.brName = row.brName
  getTableData()
  getPrescriptionCount()
  getOutpatientInfo()
}

const onReset = (e) => {
  formRef.value?.resetFields()
  tableData.value = []
  patientInfo.value = {}
  patientId.value = ''
  prescriptionCount.value = {}
  scInput.value = ''
  selectRadio.value = {}
  tabActiveKey.value = e || '自费'
}

// 打印标签
const onPrintLabel = async (row) => {
  const filteredArray = []
  row.selectedRowKeys.forEach((id) => {
    const matchedItem = row.dataSource.find((item) => item.id === id)
    if (matchedItem) {
      filteredArray.push(matchedItem)
    }
  })
  filteredArray.forEach(async (item) => {
    const { code, msg, data } = await post('/outp/outPrint/printMedicationLabels', { yzid: item.id })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
    if (item.children.length > 0) {
      item.children.forEach(async (j) => {
        const { code, msg, data } = await post('/outp/outPrint/printMedicationLabels', { yzid: j.id })
        if (code !== 0) return message.error(msg)
        window.openExe?.rpt(data) //调用winform打印
      })
    }
  })
}

// 打印处方单
const onClickPrint = async (current) => {
  if (current.dataSource?.length <= 0) return message.error('数据出错')
  if (current.dataSource[0]?.xmlb === 5) {
    //中草药
    const { code, msg, data } = await post('/outp/outPrint/getTraditionalChineseMedicinePrescriptionRaft', { cfbh: current.cfbh })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  } else {
    if (isPrint === '2') {
      const { code, msg, data } = await post('/outp/outPrint/getMedicinePrescriptionOrdersPrint', { jzbh: patientId.value })
      if (code !== 0) return message.error(msg)
      window.openExe?.rpt(data) //调用winform打印
    } else {
      const { code, msg, data } = await post('/outp/outPrint/getMedicinePrescriptionPrint', {
        cfbh: current.cfbh,
        jzbh: patientId.value,
        jklb: '1',
        printmode: 'PRINT' // PRINT：直接打印，VIEW：预览
      })
      if (code !== 0) return message.error(msg)
      window.openExe?.rpt(data) //调用winform打印1111
    }
  }
}
const getPrescriptionCount = async () => {
  const { data, code } = await post('/outp/mzys/getOutpPrescriptionQuantity', { jzbh: patientId.value, jfzt: '1' })
  if (code !== 0) return message.error('获取处方数量失败')
  prescriptionCount.value = data
}
const getDepartInfo = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取失败')
  drugStoreId.value = res.data?.defaultStoreId
}

onMounted(() => {
  getSelectPharmacist()
  const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingDrugStoreId'))
  if (drugStoreIdValue && drugStoreIdValue.value) {
    drugStoreId.value = drugStoreIdValue.value
  } else {
    getDepartInfo()
  }
  isArmy.value = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
  window.history.pushState(null, null, window.location.href + '?type=' + showType)
})
const isCheckTcCode = getSystemConfig('IS_CHECK_TCCODE_CORRECT_WHEN_DISPENSING') === '1' //发药进行追溯码的正确性校验  0：不启用|1：启用
const scInput = ref('')
const findScRow = (list, ypbh) => {
  // 查找 list.dataSource 中 sfxmbh 等于 ypbh 的数据
  const mainData = list.dataSource.find((item) => item.sfxmbh === ypbh)
  if (mainData) {
    return mainData
  }

  // 如果没有找到，查找 list.dataSource.children 中 sfxmbh 等于 ypbh 的数据
  if (list.dataSource.children) {
    return list.dataSource.children.find((item) => item.sfxmbh === ypbh)
  }
  // 如果都没有找到，返回 null 或者 undefined
  return null
}
const onCodeEnter = async () => {
  // IS_CHECK_TCCODE_CORRECT_WHEN_DISPENSING 发药进行追溯码的正确性校验  0：不启用|1：启用
  // if (!isCheckTcCode && !selectRadio.value.sfxmbh) {
  //   return message.warning('请选择一款药品进行扫码发药')
  // }
  await new Promise((resolve) => setTimeout(resolve, 200))
  if (!scInput.value) return message.error('请扫码')
  const {
    data = {},
    msg,
    code
  } = await post('/outp/outpTraceCode/doScanDistributeTraceCodeRecord', {
    jzbh: patientId.value,
    tcCode: scInput.value,
    ypbh: selectRadio.value.sfxmbh,
    drugStoreId: drugStoreId.value
  })
  if (code === 1) return message.error(msg || '失败')
  if (code === 2) {
    if (!isCheckTcCode && !selectRadio.value.sfxmbh) {
      return message.warning('请选择一款药品进行扫码发药')
    }
  }
  // canSoldSeparately   是否可以拆零,若可以拆零支持重复扫同一个码|0:false 1:true
  for (let i = 0; i < tableData.value.length; i++) {
    const cfList = tableData.value[i]
    const scRow = findScRow(cfList, data.ypbh) || {}
    if (scRow.isScAll) return message.error(`【${data.ypmc}】追溯码已扫完`)
    if (scRow.mc) {
      if (scRow.scList?.find((item) => item === scInput.value) && data.canSoldSeparately === 0) {
        message.error(`【${data.ypmc}】追溯码重复`)
        scInput.value = ''
        return
      } else {
        if (data.canSoldSeparately === 1 && data.remaining <= scRow.scList) return message.error('该盒码已扫完请另起一盒')
        scRow.scList = [...(scRow.scList || []), scInput.value]
        scRow.isScAll = scRow.scList.length === scRow.sl
        scInput.value = ''
        message.success(`【${data.ypmc}】扫码成功`)
        return
      }
    }
    scInput.value = ''
    // if (!scRow.mc && i === tableData.value.length - 1) {
    //   message.error(`【${data.ypmc}】追溯码已扫完`)
    //   scInput.value = ''
    // }
  }
}
const scInputRef = ref(null)
const onChangeRadio = (record) => {
  if (selectRadio.value.sfxmbh === record.sfxmbh) {
    selectRadio.value = {}
    return
  }
  scInputRef.value.focus()
  selectRadio.value = record
  drugInfo.value = record || {}
}

const onReadCard = async (info) => {
  const brId = info.ybkResonse?.br_id
  if (brId) {
    getList({ brId, stdate: searchData.value['dateRange']?.[0], eddate: searchData.value['dateRange']?.[1] })
  } else {
    message.error('没有数据')
  }
}
</script>

<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
